<script setup lang="ts">

import { computed, reactive, ref } from 'vue'
import { ElNotification, FormInstance, FormRules } from 'element-plus'
import { Back } from '@element-plus/icons-vue'
import { useSystemStore } from '@renderer/store/pinia/system'
import { usePresetStore } from '@renderer/store/pinia/preset'
import { postWithAns } from '@renderer/api/http'
import API from '@renderer/api/constant'
import { useRouter } from 'vue-router'
import routeConstants from '@renderer/routers/routeConstants'
import { GlobalNotification } from '@renderer/components/Toast/GlobalNotification'

const ruleFormRef = ref<FormInstance>()
const router = useRouter()

const validateUsername = (_: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('Please input the username'))
  }
}

const validatePassword = (_: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('Please input the password'))
  } else {
    callback()
  }
}


const ruleForm = reactive({
  username: '',
  password: ''
})

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }]
})

const submitForm = async (formEl: any) => {
  await formEl.validate(async (valid) => {
    if (valid) {
      await loginAction()
    } else {
      console.log('error submit!')
      return Promise.reject()
    }
  })
}

const loginAction = async () => {
  const res: any = await postWithAns(API.login, null, {
    username: ruleForm.username,
    password: ruleForm.password
  })
  const systemStore = useSystemStore()
  systemStore.userID = res.userId
  systemStore.username = ruleForm.username;
  try {
    await router.push(routeConstants.HomePage.path)
  }catch (e) {

  }finally {
    GlobalNotification({
      title: 'tips',
      message: 'login Successfully!',
      type: 'success',
    })
  }

}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const store = usePresetStore()
const systemStore = useSystemStore()
const userId = computed(() => systemStore.userID)
const showReturnFlag = computed(() => userId.value !== '')
const hasEmergency = computed(() => store.presetConfig.hasEmergency)
</script>

<template>
  <div class="w-full h-full flex justify-center items-center">
    <div class="w-[500px] h-[408px] m-auto">
      <el-card>
        <template #header>
          <div class="card-header">
            <span class="font-black text-2xl">Login</span>
          </div>
        </template>
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
        >
          <el-form-item label="Username" prop="pass">
            <el-input v-model="ruleForm.username" autocomplete="off" autofocus />
          </el-form-item>

          <el-form-item label="Password" prop="pass">
            <el-input v-model="ruleForm.password" type="password" autocomplete="off" />
          </el-form-item>

          <el-form-item>
            <div class="w-full flex justify-between ">
              <div>
                <el-button class="mr-auto" v-if="showReturnFlag" @click="router.back()">
                  <el-icon>
                    <Back />
                  </el-icon>
                  <span>返回</span>
                </el-button>

                <el-button v-if="(!showReturnFlag) && hasEmergency" class="ml-auto" type="warning">紧急访问</el-button>

              </div>
              <div>
                <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                  登录
                </el-button>
              </div>

            </div>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<style scoped>

</style>
